package at.fhooe.mc.master.clc.client.widget;

import java.util.HashSet;
import java.util.Set;

import at.fhooe.mc.master.clc.client.widget.interfaces.ICheckBoxTable;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlexTable;

public class CheckBoxTable extends FlexTable implements ICheckBoxTable {

	public void selectRow( int row ) {
		getRowFormatter().addStyleName( row, "selected" );
	}

	public void unSelectRow( int row ) {
		getRowFormatter().removeStyleName( row, "selected" );
	}

	public int getRowForEvent( ClickEvent event ) {
		return getCellForEvent( event ).getRowIndex();
	}

	@Override
	public void addRow(String... fields)
	{
		int row = getRowCount();
		
		setWidget(row, 0, new CheckBox());
		
		for (int i = 0; i < fields.length; i++)
		{
			setText(row, i + 1, fields[i]);
		}
	}
	
	@Override
	public void addRow(boolean enable, String... fields)
	{
		int row = getRowCount();
		
		CheckBox box = new CheckBox();
		box.setEnabled(enable);
		
		setWidget(row, 0, box);
		
		for (int i = 0; i < fields.length; i++)
		{
			setText(row, i + 1, fields[i]);
		}
	}

	@Override
	public Set<Integer> getSelectedRows()
	{
		Set<Integer> selectedRows = new HashSet<Integer>();
	    
	    for (int i = 0; i < getRowCount(); ++i) {
	      CheckBox checkBox = (CheckBox)getWidget(i, 0);
	      if (checkBox.getValue()) {
	        selectedRows.add(i);
	      }
	    }
	    
	    return selectedRows;
	}

	@Override
	public void addClickedRow(boolean clicked, String... fields)
	{
		int row = getRowCount();
		
		CheckBox box = new CheckBox();
		box.setValue(clicked);
		
		setWidget(row, 0, box);
		
		for (int i = 0; i < fields.length; i++)
		{
			setText(row, i + 1, fields[i]);
		}
	}

}
